<template>
  <div class="scheduling-container">
    <!-- 统计卡片 -->
    <div class="stats-row">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
            <el-icon :size="24">
              <Document />
            </el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ totalTasks }}</div>
            <div class="stat-label">总工序数</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
            <el-icon :size="24">
              <Loading />
            </el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ inProgressTasks }}</div>
            <div class="stat-label">进行中</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
            <el-icon :size="24">
              <CircleCheck />
            </el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ completedTasks }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
            <el-icon :size="24">
              <Warning />
            </el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ overdueTasks }}</div>
            <div class="stat-label">已逾期</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 甘特图卡片 -->
    <el-card class="gantt-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon" :size="20">
              <Calendar />
            </el-icon>
            <span class="card-title">工艺工序甘特图</span>
          </div>
          <div class="header-right">
            <el-button type="primary" size="small" :icon="Refresh" @click="GetProduction" :loading="loading">
              刷新数据
            </el-button>
          </div>
        </div>
      </template>
      <div class="ed-page">
        <vxe-gantt v-bind="ganttOptions"></vxe-gantt>
      </div>
    </el-card>

    <!-- 表格卡片 -->
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon" :size="20">
              <List />
            </el-icon>
            <span class="card-title">工序详细列表</span>
          </div>
          <div class="header-right">
            <el-input v-model="searchText" placeholder="搜索工序名称..." :prefix-icon="Search" size="small" clearable
              style="width: 200px; margin-right: 10px;" />
            <el-button size="small" :icon="Download">导出</el-button>
          </div>
        </div>
      </template>
      <el-table :data="filteredTableData" style="width: 100%" height="450" stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
        <el-table-column fixed type="index" label="序号" width="60" align="center" />
        <el-table-column fixed prop="plannumber" label="计划编号" width="140" show-overflow-tooltip />
        <el-table-column prop="processname" label="工艺工序名称" width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="process-name">
              <el-icon color="#409eff">
                <Tools />
              </el-icon>
              <span style="margin-left: 8px;">{{ row.processname }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="kahuna" label="负责人" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.kahuna" type="info" size="small">{{ row.kahuna }}</el-tag>
            <span v-else style="color: #c0c4cc;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="goodsname" label="产品名称" width="150" show-overflow-tooltip />
        <el-table-column prop="goodtime" label="制作时间" width="170" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.goodtime) }}
          </template>
        </el-table-column>
        <el-table-column prop="planstate" label="计划状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.planstate === 1" type="success" size="small">已启动</el-tag>
            <el-tag v-else-if="row.planstate === 0" type="info" size="small">未启动</el-tag>
            <el-tag v-else type="warning" size="small">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="planstatetime" label="计划开始" width="170" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.planstatetime) }}
          </template>
        </el-table-column>
        <el-table-column prop="planendtime" label="计划结束" width="170" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.planendtime) }}
          </template>
        </el-table-column>
        <el-table-column prop="statetime" label="实际开始" width="170" align="center">
          <template #default="{ row }">
            <span :class="{ 'highlight-time': row.statetime }">{{ formatDateTime(row.statetime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="endtime" label="实际结束" width="170" align="center">
          <template #default="{ row }">
            <span :class="{ 'highlight-time': row.endtime }">{{ formatDateTime(row.endtime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="equipmentname" label="设备名称" width="150" show-overflow-tooltip />
        <el-table-column prop="manager" label="设备负责人" width="110" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.manager" type="success" size="small">{{ row.manager }}</el-tag>
            <span v-else style="color: #c0c4cc;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderNumber" label="订单数量" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.orderNumber" effect="plain">{{ row.orderNumber }}</el-tag>
            <span v-else style="color: #c0c4cc;">-</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button link type="primary" size="small" :icon="View" @click="handleView(row)">查看</el-button>
            <el-button link type="primary" size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 详情模态框 -->
    <el-dialog v-model="detailDialogVisible" title="工序详细信息" width="800px" :close-on-click-modal="false" draggable>
      <div v-if="currentDetail" class="detail-container">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="计划编号" label-class-name="detail-label">
            <el-tag type="info">{{ currentDetail.plannumber || '-' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="工序ID" label-class-name="detail-label">
            {{ currentDetail.id || '-' }}
          </el-descriptions-item>

          <el-descriptions-item label="工艺工序名称" label-class-name="detail-label" :span="2">
            <div class="detail-title">
              <el-icon color="#409eff">
                <Tools />
              </el-icon>
              <span>{{ currentDetail.processname || '-' }}</span>
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="工序负责人" label-class-name="detail-label">
            <el-tag v-if="currentDetail.kahuna" type="success">{{ currentDetail.kahuna }}</el-tag>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="设备负责人" label-class-name="detail-label">
            <el-tag v-if="currentDetail.manager" type="success">{{ currentDetail.manager }}</el-tag>
            <span v-else>-</span>
          </el-descriptions-item>

          <el-descriptions-item label="产品名称" label-class-name="detail-label">
            {{ currentDetail.goodsname || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="订单数量" label-class-name="detail-label">
            <el-tag v-if="currentDetail.orderNumber" effect="plain">{{ currentDetail.orderNumber }}</el-tag>
            <span v-else>-</span>
          </el-descriptions-item>

          <el-descriptions-item label="产品制作时间" label-class-name="detail-label">
            {{ formatDateTime(currentDetail.goodtime) }}
          </el-descriptions-item>
          <el-descriptions-item label="设备名称" label-class-name="detail-label">
            {{ currentDetail.equipmentname || '-' }}
          </el-descriptions-item>

          <el-descriptions-item label="计划状态" label-class-name="detail-label">
            <el-tag v-if="currentDetail.planstate === 1" type="success">已启动</el-tag>
            <el-tag v-else-if="currentDetail.planstate === 0" type="info">未启动</el-tag>
            <el-tag v-else type="warning">未知</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="当前进度" label-class-name="detail-label">
            <el-progress :percentage="calculateCurrentProgress(currentDetail)"
              :color="getProgressColorValue(calculateCurrentProgress(currentDetail))" />
          </el-descriptions-item>

          <el-descriptions-item label="计划开始时间" label-class-name="detail-label">
            <el-text type="info">{{ formatDateTime(currentDetail.planstatetime) }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="计划结束时间" label-class-name="detail-label">
            <el-text type="info">{{ formatDateTime(currentDetail.planendtime) }}</el-text>
          </el-descriptions-item>

          <el-descriptions-item label="实际开始时间" label-class-name="detail-label">
            <el-text type="primary" class="highlight-time">{{ formatDateTime(currentDetail.statetime) }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="实际结束时间" label-class-name="detail-label">
            <el-text type="primary" class="highlight-time">{{ formatDateTime(currentDetail.endtime) }}</el-text>
          </el-descriptions-item>

          <el-descriptions-item label="持续天数" label-class-name="detail-label">
            <el-tag v-if="currentDetail.statetime && currentDetail.endtime" type="warning">
              {{ calculateDurationDays(currentDetail.statetime, currentDetail.endtime) }} 天
            </el-tag>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="工序状态" label-class-name="detail-label">
            <el-tag :type="getStatusTagType(currentDetail)">
              {{ getProcessStatus(currentDetail) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEdit(currentDetail)">编辑</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import myaxios from '@/Http/http'
import { reactive, onMounted, onUnmounted, ref, computed } from 'vue'
import {
  Refresh, Calendar, List, Search, Download, Tools, View, Edit,
  Document, Loading, CircleCheck, Warning
} from '@element-plus/icons-vue'
import * as signalR from '@microsoft/signalr'
import { ElMessage } from 'element-plus'
import { signalRConfig, HubMethods } from '@/config/signalr'

const tableData = ref([{
  "id": null,
  "plannumber": "",
  "processname": "",
  "kahuna": "",
  "goodsname": "",
  "goodtime": "",
  "planstate": null,
  "planstatetime": "",
  "planendtime": "",
  "statetime": "",
  "endtime": "",
  "equipmentname": "",
  "manager": "",
  "orderNumber": null
},])

const loading = ref(false)
const searchText = ref('')
let hubConnection = null
let pollingTimer = null // 定时器
const pollingInterval = signalRConfig.pollingInterval // 轮询间隔（从配置文件读取）

// 详情模态框
const detailDialogVisible = ref(false)
const currentDetail = ref(null)

// 搜索过滤
const filteredTableData = computed(() => {
  if (!searchText.value) return tableData.value
  return tableData.value.filter(item =>
    item.processname?.toLowerCase().includes(searchText.value.toLowerCase())
  )
})

// 统计数据
const totalTasks = computed(() => tableData.value.filter(item => item.id).length)
const inProgressTasks = computed(() => {
  return tableData.value.filter(item => {
    if (!item.statetime || !item.endtime) return false
    const now = new Date()
    const start = new Date(item.statetime)
    const end = new Date(item.endtime)
    return now >= start && now <= end
  }).length
})
const completedTasks = computed(() => {
  return tableData.value.filter(item => {
    if (!item.endtime) return false
    const now = new Date()
    const end = new Date(item.endtime)
    return now > end
  }).length
})
const overdueTasks = computed(() => {
  return tableData.value.filter(item => {
    if (!item.planendtime || !item.endtime) return false
    const planEnd = new Date(item.planendtime)
    const actualEnd = new Date(item.endtime)
    return actualEnd > planEnd
  }).length
})

const GetProduction = () => {
  loading.value = true
  myaxios.get('api/Production').then((res) => {
    console.log(res)
    if (res.data.code == 200) {
      tableData.value = res.data.listResult
      // 更新甘特图数据
      updateGanttData()
    }
  }).finally(() => {
    loading.value = false
  })
}

// 查看详情
const handleView = (row) => {
  currentDetail.value = row
  detailDialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  ElMessage.info(`编辑功能开发中：${row.processname}`)
  // TODO: 实现编辑功能
}

// 计算当前进度
const calculateCurrentProgress = (item) => {
  if (!item.statetime || !item.endtime) return 0

  const startDate = new Date(item.statetime)
  const endDate = new Date(item.endtime)
  const currentDate = new Date()

  if (currentDate < startDate) return 0
  if (currentDate > endDate) return 100

  const totalDuration = endDate.getTime() - startDate.getTime()
  const elapsedDuration = currentDate.getTime() - startDate.getTime()

  return Math.min(100, Math.max(0, Math.round((elapsedDuration / totalDuration) * 100)))
}

// 获取进度条颜色值
const getProgressColorValue = (progress) => {
  if (progress < 20) return '#ff4d4f'
  if (progress < 50) return '#ffa940'
  if (progress < 80) return '#40a9ff'
  return '#52c41a'
}

// 计算持续天数
const calculateDurationDays = (start, end) => {
  if (!start || !end) return 0
  const startDate = new Date(start)
  const endDate = new Date(end)
  const timeDiff = endDate.getTime() - startDate.getTime()
  return Math.ceil(timeDiff / (1000 * 3600 * 24))
}

// 获取工序状态
const getProcessStatus = (item) => {
  if (!item.statetime || !item.endtime) return '未开始'

  const startDate = new Date(item.statetime)
  const endDate = new Date(item.endtime)
  const currentDate = new Date()

  if (currentDate > endDate) return '已完成'
  if (currentDate < startDate) return '未开始'
  if (currentDate >= startDate && currentDate <= endDate) return '进行中'

  return '未知'
}

// 获取状态标签类型
const getStatusTagType = (item) => {
  const status = getProcessStatus(item)
  if (status === '已完成') return 'success'
  if (status === '进行中') return 'primary'
  if (status === '未开始') return 'info'
  return 'warning'
}

// 更新甘特图数据
const updateGanttData = () => {
  if (!tableData.value || tableData.value.length === 0) return

  ganttOptions.data = tableData.value
    .filter(item => item.statetime && item.endtime) // 只显示有实际时间的数据
    .map(item => ({
      id: item.id,
      title: item.processname || '未命名工序',
      start: formatDate(item.statetime), // 甘特图时间轴用日期
      end: formatDate(item.endtime), // 甘特图时间轴用日期
      startFull: item.statetime, // 保存完整时间用于列显示
      endFull: item.endtime, // 保存完整时间用于列显示
      progress: calculateProgress(item),
      responsible: item.kahuna || '',
      equipment: item.equipmentname || '',
      plannumber: item.plannumber || ''
    }))
}

// 格式化日期为 YYYY-MM-DD（用于甘特图）
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  if (isNaN(date.getTime())) return '-'

  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  return `${year}-${month}-${day}`
}

// 格式化日期时间为 YYYY-MM-DD HH:mm:ss
const formatDateTime = (dateString) => {
  if (!dateString) return '-'

  // 先替换掉 T 字符
  const cleanDateString = dateString.replace('T', ' ')

  const date = new Date(cleanDateString)
  if (isNaN(date.getTime())) return '-'

  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 计算进度（根据实际情况调整）
const calculateProgress = (item) => {
  if (!item.statetime || !item.endtime) return 0

  const startDate = new Date(item.statetime)
  const endDate = new Date(item.endtime)
  const currentDate = new Date()

  // 如果还未开始
  if (currentDate < startDate) return 0

  // 如果已经结束
  if (currentDate > endDate) return 100

  // 计算进度百分比
  const totalDuration = endDate.getTime() - startDate.getTime()
  const elapsedDuration = currentDate.getTime() - startDate.getTime()

  return Math.min(100, Math.max(0, Math.round((elapsedDuration / totalDuration) * 100)))
}

// 初始化 SignalR 连接
const initSignalR = async () => {
  try {
    // 创建 SignalR 连接
    hubConnection = new signalR.HubConnectionBuilder()
      .withUrl(signalRConfig.hubUrl, signalRConfig.options)
      .withAutomaticReconnect(signalRConfig.reconnectDelays)
      .configureLogging(signalRConfig.logLevel)
      .build()

    // 监听生产数据更新事件
    hubConnection.on(HubMethods.PRODUCTION_UPDATED, (data) => {
      console.log('收到生产数据更新:', data)
      // 更新表格数据
      if (data && Array.isArray(data)) {
        tableData.value = data
      } else if (data && data.listResult) {
        tableData.value = data.listResult
      }
      // 更新甘特图
      updateGanttData()
      ElMessage.success('生产数据已更新')
    })

    // 监听单个工序更新事件
    hubConnection.on(HubMethods.PROCESS_UPDATED, (process) => {
      console.log('收到工序更新:', process)
      const index = tableData.value.findIndex(item => item.id === process.id)
      if (index !== -1) {
        tableData.value[index] = process
        updateGanttData()
      }
    })

    // 监听工序开始事件
    hubConnection.on(HubMethods.PROCESS_STARTED, (process) => {
      console.log('工序已开始:', process)
      const index = tableData.value.findIndex(item => item.id === process.id)
      if (index !== -1) {
        tableData.value[index] = process
        updateGanttData()
        ElMessage.info(`工序 "${process.processname}" 已开始`)
      }
    })

    // 监听工序完成事件
    hubConnection.on(HubMethods.PROCESS_COMPLETED, (process) => {
      console.log('工序已完成:', process)
      const index = tableData.value.findIndex(item => item.id === process.id)
      if (index !== -1) {
        tableData.value[index] = process
        updateGanttData()
        ElMessage.success(`工序 "${process.processname}" 已完成`)
      }
    })

    // 连接状态变化监听
    hubConnection.onreconnecting((error) => {
      console.warn('SignalR 重新连接中...', error)
      ElMessage.warning('连接断开，正在重新连接...')
    })

    hubConnection.onreconnected((connectionId) => {
      console.log('SignalR 重新连接成功:', connectionId)
      ElMessage.success('连接已恢复')
      // 重新获取数据
      GetProduction()
    })

    hubConnection.onclose((error) => {
      console.error('SignalR 连接关闭:', error)
      ElMessage.error('连接已断开')
    })

    // 启动连接
    await hubConnection.start()
    console.log('SignalR 连接成功')
    ElMessage.success('实时连接已建立')
  } catch (error) {
    console.error('SignalR 连接失败:', error)
    ElMessage.error('实时连接失败，将使用轮询模式')
  }
}

// 断开 SignalR 连接
const disconnectSignalR = async () => {
  if (hubConnection) {
    try {
      await hubConnection.stop()
      console.log('SignalR 连接已断开')
    } catch (error) {
      console.error('断开 SignalR 连接失败:', error)
    }
  }
}

// 启动定时轮询
const startPolling = () => {
  // 清除已存在的定时器
  if (pollingTimer) {
    clearInterval(pollingTimer)
  }

  // 设置定时器，定期调用 GetProduction
  pollingTimer = setInterval(() => {
    console.log('定时轮询：获取生产数据')
    GetProduction()
  }, pollingInterval)

  console.log(`定时轮询已启动，间隔 ${pollingInterval / 1000} 秒`)
}

// 停止定时轮询
const stopPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
    console.log('定时轮询已停止')
  }
}

onMounted(() => {
  // 首次加载数据
  GetProduction()
  // 初始化 SignalR 连接
  initSignalR()
  // 启动定时轮询
  startPolling()
})

onUnmounted(() => {
  // 组件卸载时停止定时轮询
  stopPolling()
  // 断开 SignalR 连接
  disconnectSignalR()
})
/**
 * 计算任务持续时间（天数）
 * @param {string} start - 开始日期
 * @param {string} end - 结束日期
 * @returns {number} 持续天数
 */
function calculateDuration(start, end) {
  const startDate = new Date(start)
  const endDate = new Date(end)
  const timeDiff = endDate.getTime() - startDate.getTime()
  return Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1
}

/**
 * 根据进度值获取进度条颜色
 * @param {number} progress - 进度值（0-100）
 * @returns {string} 颜色值
 */
function getProgressColor(progress) {
  if (progress < 20) {
    return '#ff4d4f' // 红色 - 进度很低
  } else if (progress < 50) {
    return '#ffa940' // 橙色 - 进度较低
  } else if (progress < 80) {
    return '#40a9ff' // 蓝色 - 进度中等
  } else {
    return '#52c41a' // 绿色 - 进度很高
  }
}

/**
 * 检查任务是否逾期（精确到秒）
 * @param {Object} row - 行数据对象
 * @param {string} row.startFull - 完整开始时间
 * @param {string} row.endFull - 完整结束时间
 * @param {string} row.start - 开始日期（备用）
 * @param {string} row.end - 结束日期（备用）
 * @param {number} row.progress - 进度值
 * @returns {boolean} 是否逾期
 */
function isOverdue(row) {
  // 如果任务已完成，则不会逾期
  if (row.progress === 100) {
    return false
  }

  // 使用完整时间进行精确判断（精确到秒）
  const endDate = new Date(row.endFull || row.end)
  const currentDate = new Date()

  // 如果当前时间已经超过结束时间，则为逾期（精确到秒）
  return currentDate > endDate
}

const ganttOptions = reactive({
  border: true,
  taskBarConfig: {
    showProgress: true,
    showContent: true,

    /**
     * 根据进度值和时间状态设置任务条背景颜色（精确到秒）
     * @param {Object} options - 配置对象
     * @param {Object} options.row - 行数据对象
     * @param {string} options.row.startFull - 完整开始时间
     * @param {string} options.row.endFull - 完整结束时间
     * @param {string} options.row.start - 开始日期（备用）
     * @param {string} options.row.end - 结束日期（备用）
     * @param {number} options.row.progress - 进度值（0-100）
     * @returns {Object} 样式对象
     */
    barStyle({ row }) {
      // 检查是否逾期（精确到秒）
      if (isOverdue(row)) {
        return {
          bgColor: '#ff6b6b', // 红色 - 逾期任务
        }
      }

      // 根据进度设置颜色
      if (row.progress < 10) {
        return {
          bgColor: '#fd9393', // 浅红色 - 进度很低
        }
      }
      if (row.progress < 30) {
        return {
          bgColor: '#fad06c', // 浅黄色 - 进度较低
        }
      }
      if (row.progress < 80) {
        return {
          bgColor: '#65c16f', // 浅绿色 - 进度中等
        }
      }
      return {
        bgColor: '#4aeaf2', // 蓝青色 - 进度很高
      }
    },

    /**
     * 格式化进度显示内容
     * @param {Object} options - 配置对象
     * @param {Object} options.row - 行数据对象
     * @param {number} options.row.progress - 进度值（0-100）
     * @returns {string} 格式化后的进度文本，格式为 "{progress}%"
     */
    contentMethod({ row }) {
      return `${row.progress}%`
    },

    /**
     * 根据进度值设置进度条颜色
     * @param {Object} options - 配置对象
     * @param {Object} options.row - 行数据对象
     * @param {number} options.row.progress - 进度值（0-100）
     * @returns {string} 进度条颜色值
     */
    progressColorMethod({ row }) {
      return getProgressColor(row.progress)
    },
  },
  columns: [
    { field: 'title', title: '工艺工序名称', width: 200 },
    {
      field: 'start',
      title: '实际开始时间',
      width: 170,
      formatter: ({ row }) => {
        return formatDateTime(row.startFull || row.start)
      }
    },
    {
      field: 'end',
      title: '实际结束时间',
      width: 170,
      formatter: ({ row }) => {
        return formatDateTime(row.endFull || row.end)
      }
    },
    {
      field: 'duration',
      title: '持续天数',
      width: 100,
      formatter: ({ row }) => {
        const duration = calculateDuration(row.start, row.end)
        return `${duration}天`
      },
    },
    {
      field: 'progress',
      title: '进度',
      width: 100,
      formatter: ({ row }) => {
        return `${row.progress}%`
      },
    },
    {
      field: 'responsible',
      title: '负责人',
      width: 100,
    },
    {
      field: 'equipment',
      title: '设备名称',
      width: 150,
    },
    {
      field: 'status',
      title: '状态',
      width: 100,
      formatter: ({ row }) => {
        // 使用完整时间进行精确判断（精确到秒）
        const startDate = new Date(row.startFull || row.start)
        const endDate = new Date(row.endFull || row.end)
        const currentDate = new Date()

        // 如果已经结束（精确到秒）
        if (currentDate > endDate) {
          return '已完成'
        }

        // 如果还未开始（精确到秒）
        if (currentDate < startDate) {
          return '未开始'
        }

        // 如果在进行中（精确到秒）
        if (currentDate >= startDate && currentDate <= endDate) {
          return '进行中'
        }

        return '未知'
      },
    },
  ],
  data: [],
})
</script>

<style scoped>
.scheduling-container {
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

/* 统计卡片行 */
.stats-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  transition: all 0.3s ease;
  cursor: pointer;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 8px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

/* 卡片样式 */
.gantt-card,
.table-card {
  margin-bottom: 24px;
  border-radius: 12px;
  border: none;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.gantt-card:hover,
.table-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.header-left,
.header-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  color: #409eff;
}

.card-title {
  font-weight: 600;
  font-size: 18px;
  color: #303133;
  letter-spacing: 0.5px;
}

.ed-page {
  min-height: 450px;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 8px;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-table tbody tr:hover) {
  background-color: #f5f7fa;
}

:deep(.el-table__body tr.current-row > td) {
  background-color: #ecf5ff;
}

/* 工序名称样式 */
.process-name {
  display: flex;
  align-items: center;
  font-weight: 500;
}

/* 高亮时间 */
.highlight-time {
  color: #409eff;
  font-weight: 500;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5568d3 0%, #6a3f8f 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* 输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  font-weight: 500;
}

/* 卡片内容区域 */
:deep(.el-card__body) {
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .scheduling-container {
    padding: 16px;
  }

  .stats-row {
    grid-template-columns: 1fr;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .header-right {
    width: 100%;
    justify-content: space-between;
  }
}

/* 详情模态框样式 */
.detail-container {
  padding: 10px 0;
}

:deep(.detail-label) {
  font-weight: 600;
  background-color: #f5f7fa;
}

.detail-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-descriptions__label) {
  width: 140px;
}

:deep(.el-descriptions__content) {
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  margin: 0;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 20px;
}

:deep(.el-dialog__headerbtn .el-dialog__close:hover) {
  color: #f0f0f0;
}

:deep(.el-dialog__body) {
  padding: 20px;
  max-height: 600px;
  overflow-y: auto;
}
</style>
